﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Blog.Core;

namespace Blog.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        [OutputCache(CacheProfile = "CacheHome1Hour")]
        public ActionResult Index()
        {
            ViewData.Model = ViewController.GetThemes();
            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        [Authorize(Roles = "Administrator")]
        public ActionResult Delete(int id)
        {
            ViewData.Model = ViewController.GetTheme(id);
            return View();
        }

        [HttpPost]
        [Authorize(Roles = "Administrator")]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                ViewController.DeleteTheme(id);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        [Authorize(Roles = "Administrator")]
        public ActionResult Edit(int id)
        {
            ViewData.Model = ViewController.GetTheme(id);
            return View();
        }

        [HttpPost]
        [Authorize(Roles = "Administrator")]
        public ActionResult Edit(int id, FormCollection collection)
        {
            string header = string.Empty;
            try
            {
                header = collection["ThemeHeader"];
                string context = collection["Description"];
                
                if (!string.IsNullOrEmpty(context))
                    context = Server.UrlDecode(context);

                if (string.IsNullOrEmpty(header.Trim()))
                    throw new Exception("Требуется наименование темы");

                ViewController.EditTheme(id, header, context);
                return RedirectToAction("Index");
            }
            catch (Exception exc)
            {
                ModelState.AddModelError("ThemeHeader", exc.Message);
                Theme t = ViewController.GetTheme(id);
                t.ThemeHeader = header;
                ViewData.Model = t;
                return View();
            }
        }

        public ActionResult Error(string text)
        {
            ViewData.Model = new HandleErrorInfo(new Exception(text), "", "");
            //ViewData["ErrorText"] = text;
            return View();
        }
    }

}
